var client;

jQuery.scope = function(target,func){ return function() { return func.apply(target,arguments);}};

function htmlspecialchars (ch)
{
  ch = ch.replace(/&/g,"&amp;") ;
  ch = ch.replace(/"/g,"&quot;") ;
  ch = ch.replace(/'/g,"&#039;") ;
  ch = ch.replace(/</g,"&lt;") ;
  ch = ch.replace(/>/g,"&gt;") ;
  return ch ;
}

var UserSetting = function() {
  var _isOwner = false;
  var _maxMenuNum = 30;
  var _menuAry;
  var _public;
  var _recommendTarget;
  var _lastRecommend;

  this.isOwner = function() {
    return _isOwner;
  };
  
  this.getCurrentView = function() {
    return gadgets.views.getCurrentView().getName();
  };

  this.initialize = function() {
    this.checkViewerIsOwner();
    this.getStoredData();
  };

  this.initializeForProfile = function () {
    this.getStoredData();
  };

  this.checkViewerIsOwner = function() {
    $.getData('/people/@viewer/@self', {}, $.scope(this, this.checkViewerIsOwner_Result));
  };
  
  this.checkViewerIsOwner_Result = function(people) {
    var person = people[0];  
    _isOwner = person.isOwner;
    if (this.isOwner()) {
      this.activateSetting();
    }
  };

  this.activateSetting = function() {
    $("#setting").show();
  };

  this.showForProfile = function ()
  {
    // 非公開
    if (_public == 3) {
      $('#recommendFood').html('非公開設定になっています。');
      return;
    }
    
    // 全体に公開
    if (_public == 1) {
      this.showBySetting();
      return ;
    }
    
    if (_public == 2) {
      $('#recommendFood').html('マイミクへの公開機能は開発中です。');
      return;
    }
  };

  this.showBySetting = function ()
  {
    
    if (_recommendTarget.checkBreakfast) {
      $('#breakfast').show();
    } else {
      $('#breakfast').hide();
    }
    
    if (_recommendTarget.checkLunch) {
      $('#lunch').show();
    } else {
      $('#lunch').hide();
    }
    
    if (_recommendTarget.checkDinner) {
      $('#dinner').show();
    } else {
      $('#dinner').hide();
    }
    
    $('#lastdate').show();
    
    $('#breakfastData').html(htmlspecialchars(_lastRecommend.breakfast));
    $('#lunchData').html(htmlspecialchars(_lastRecommend.lunch));
    $('#dinnerData').html(htmlspecialchars(_lastRecommend.dinner));
    $('#lastdateData').html(htmlspecialchars(_lastRecommend.date));
    
    $('#loading').hide();
  };

  /**
   * fetchStoredData
   * 永続化データを取得する
   */
  this.getStoredData = function() {
    $.getData('/appdata/@owner/@self', {}, $.scope(this, this.getStoredData_Result));
  };
  
  this.getStoredData_Result = function(data) {
    var that = this;
    $.each(data, function(userId, data) {
      that.setFoodMenus(data);
      that.setPublic(data);
      that.setRecommendTarget(data);
      that.setLastRecommend(data);
    
    });
    
    if (this.getCurrentView() != 'profile') {
      this.showBySetting();
    } else {
      this.showForProfile();
    }
  };


  this.getDefaultFoodMenu = function ()
  {
    var menus = new Array();

    menus[0] = 'ラーメン';
    menus[1] = 'とんかつ';
    menus[2] = 'ハンバーグ';
    menus[3] = '中華';
    menus[4] = '和食';
    menus[5] = '洋食';
 
    return menus;
  }

  this.getDefaultRecommendTarget = function ()
  {
      var recommendTarget = new Object();
      recommendTarget.checkBreakfast = true;
      recommendTarget.checkLunch = true;
      recommendTarget.checkDinner = true;
      return recommendTarget;
  }

  this.getDefaultLastRecommend = function ()
  {
      var lastRecommend = new Object();
      lastRecommend.breakfast = 'まだ決めてません。';
      lastRecommend.lunch = 'まだ決めてません。';
      lastRecommend.dinner = 'まだ決めてません。';
      lastRecommend.date = 'まだおすすめしていません。';
      return lastRecommend;
  }

  // メニューの設定
  this.setFoodMenus = function (data)
  {
    if (data.foodMenusData == undefined || data.foodMenusData == null || data.foodMenusData.length < 1) {
      _menuAry = this.getDefaultFoodMenu();
    } else {
      _menuAry = data.foodMenusData;
    }

    var foodMenuTag = '<table>';
    
    foodMenuTag += '<tr>';
    
    for (var i = 0; i < _menuAry.length; i++) {
      var labelIndex = (i % 3 == 0) ? 3 : (i % 3);
      foodMenuTag += '<th class="foodMenuLabel'+labelIndex+'">メニュー'+(i+1)+'</th>';
      foodMenuTag += '<td class="foodMenuData'+labelIndex+'"><input type="text" id="foodMenu'+i+'" value="'+htmlspecialchars(_menuAry[i])+'" /></td>';
      
      if ((i + 1) % 3 == 0 && (i + 1) != _maxMenuNum) {
        foodMenuTag += '</tr><tr>'
      }
    }

    for (; i < _maxMenuNum; i++) {
      foodMenuTag += '<th class="foodMenuLabel'+labelIndex+'">メニュー'+(i+1)+'</th>';
      foodMenuTag += '<td class="foodMenuData'+labelIndex+'"><input type="text" id="foodMenu'+i+'" value="" /></td>';

      if ((i + 1) % 3 == 0 && (i + 1) != _maxMenuNum) {
        foodMenuTag += '</tr><tr>'
      }
    }

    foodMenuTag += '</tr></table>';
    
    $('#foodMenus').html(foodMenuTag);
  };

  // 公開範囲
  this.setPublic = function (data)
  {
    if (data.public == undefined || data.public == null) {
      _public = 3;
    } else {
      _public = data.public;
    }
    $('#public').val(_public);
  };

  // おすすめ対象
  this.setRecommendTarget = function (data)
  {
    if (data.recommendTarget == undefined || data.recommendTarget == null) {
      _recommendTarget = this.getDefaultRecommendTarget();
    } else {
      _recommendTarget = data.recommendTarget;
    }
    
    if (_recommendTarget.checkBreakfast) {
      $('#checkBreakfast').attr('checked', true);
    }
    
    if (_recommendTarget.checkLunch) {
      $('#checkLunch').attr('checked', true);
    }
    
    if (_recommendTarget.checkDinner) {
      $('#checkDinner').attr('checked', true);
    }
  };
  
  // 直近のおすすめ結果
  this.setLastRecommend = function (data)
  {
    if (data.lastRecommend == undefined || data.lastRecommend == null) {
      _lastRecommend = this.getDefaultLastRecommend();
    } else {
      _lastRecommend = data.lastRecommend;
    }
  }

  this.deleteStoredData = function () {
    $.postData('/appdata/@viewer/@self', {
        'foodMenusData': _menuAry,
        'public' : _public,
        'recommendTarget' : _recommendTarget,
        'lastRecommend' : _lastRecommend
      }, function () { alert('設定完了'); });
  };

  /**
   * putStoredData
   * 永続化データを保存する
   */
  this.putStoredData = function(flg) {
    _menuAry = new Array();

    // メニューの作成
    j = 0;
    for (var i = 0; i < _maxMenuNum; i++) {
      var menu = $('#foodMenu'+i).val();
      
      if (menu == null || menu == undefined || menu.length < 1) continue;
      _menuAry[j] = menu;
      j++;
    }

    // 公開範囲
    _public = $('#public').val();
    
    var allDisableFlg = true;
    _recommendTarget = new Object();
    if ($('#checkBreakfast').attr("checked")) {
      _recommendTarget.checkBreakfast = true;
      allDisableFlg = false;
    } else {
      _recommendTarget.checkBreakfast = false;
    }

    if ($('#checkLunch').attr("checked")) {
      _recommendTarget.checkLunch = true;
      allDisableFlg = false;
    } else {
      _recommendTarget.checkLunch = false;
    }

    if ($('#checkDinner').attr("checked")) {
      _recommendTarget.checkDinner = true;
      allDisableFlg = false;
    } else {
      _recommendTarget.checkDinner = false;
    }
    
    if (allDisableFlg) {
      alert('おすすめ対象は最低1つは設定して下さい。');
      return;
    }
    
    if (flg == undefined || flg == null) {
      $.postData('/appdata/@viewer/@self', {
        'foodMenusData': _menuAry,
        'public' : _public,
        'recommendTarget' : _recommendTarget,
        'lastRecommend' : _lastRecommend
      }, function () { alert('設定完了'); });
    } else {
      $.postData('/appdata/@viewer/@self', {
        'foodMenusData': _menuAry,
        'public' : _public,
        'recommendTarget' : _recommendTarget,
        'lastRecommend' : _lastRecommend
      }, function () {});
    }
    
    this.showBySetting();
  };

  this.dispContentTab = function ()
  {

  };

  this.dispFoodMenuTab = function ()
  {
    if (!this.isOwner()) {
      $('#foodMenus').html('アプリをインストールして下さい。');
      return ;
    }
  };

  this.dispRecommendMenuTab = function ()
  {
    if (!this.isOwner()) {
      $('#recommendMenuTab').html('アプリをインストールして下さい。');
      return ;
    }
  };

  this.getRecommendFood = function ()
  {
    var tmpAry = new Array();

    if (_menuAry.length < 3) {
      alert("メニューがかぶっちゃうよ！");
      return ;
    }

    for (var i = 0; i < _menuAry.length; i++) {
      tmpAry[i] = _menuAry[i];
    }
    
    var index = 0;
    var length = tmpAry.length;
    
    _lastRecommend = new Object();

    index = Math.floor(Math.random() * length);
    var breakfast = tmpAry[index];
    _lastRecommend.breakfast = breakfast;
    tmpAry.splice(index, 1);

    index = Math.floor(Math.random() * (length - 1));
    var lunch = tmpAry[index];
    _lastRecommend.lunch = lunch;
    tmpAry.splice(index, 1);

    index = Math.floor(Math.random() * (length - 2));
    var dinner = tmpAry[index];
    _lastRecommend.dinner = dinner;
    tmpAry.splice(index, 1);
    
    _lastRecommend.date = this.getNowDate();

    $('#breakfastData').html(htmlspecialchars(breakfast));
    $('#lunchData').html(htmlspecialchars(lunch));
    $('#dinnerData').html(htmlspecialchars(dinner));
    $('#lastdateData').html(_lastRecommend.date);

    this.putStoredData(true);
  };

  this.dispOtherTab = function ()
  {
  };

  this.getNowDate = function ()
  {
    d = new Date();
    var year = d.getYear();
    if (year < 2000) {
      year = 1900 + year;
    }
    return year + '年' + (d.getMonth() + 1) + '月' + d.getDate() + '日' + d.getHours() + '時' + d.getMinutes() + '分';
  };
};
